package com.ls.bjtool.utils;



import com.ls.bjtool.bean.RequestBean;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class HttpUtil {
    private static ThreadLocal<RequestBean> RequestBeanThreadLocal = new ThreadLocal<RequestBean>();

    //从当前线程变量中获取用户信息
    public static RequestBean getRequestInfo() {
        RequestBean RequestBean = RequestBeanThreadLocal.get();
        return RequestBean;
    }


    //为当前的线程变量赋值上用户信息
    public static void setRequestInfo(RequestBean RequestBean) {
        RequestBeanThreadLocal.set(RequestBean);
    }

    //清除线程变量
    public static void removeRequestInfo() {
        RequestBeanThreadLocal.remove();
    }

    public static String getIPAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if (ip.equals("127.0.0.1") || ip.equals("0:0:0:0:0:0:0:1")) {
                try {
                    InetAddress inet = InetAddress.getLocalHost();
                    ip = inet.getHostAddress();
                } catch (UnknownHostException var3) {
                    return "";
                }
            }
        }

        if (ip != null && ip.length() > 15 && ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
        }

        return ip;
    }
}
